package com.example.security.springboot.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yingyuwei
 * @version 1.0.0
 * @description TODO
 * @createTime 2021年02月27日 16:07:00
 */
@RestController
public class LoginController {

    @RequestMapping(value = "login‐success", produces="text/html;charset=UTF-8")
    public String loginSuccess() {
        return getUsername() + ",登录成功";
    }
    @RequestMapping(value = "/api/user/info", produces="text/html;charset=UTF-8")
    @PreAuthorize("isAnonymous()")
    public String userInfo() {
        return getUsername();
    }

    private String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        String userName = null;
        if (principal instanceof UserDetails) {
            userName = ((UserDetails) principal).getUsername();
        } else {
            userName = principal.toString();
        }

        return userName;
    }
}
